package com.example.tool.conf;

import cn.hutool.core.util.ObjectUtil;
import com.example.tool.erp.sdk.api.goods.dto.GoodsSearchResponse;
import com.example.tool.erp.sdk.api.wms.dto.StockSearch2Response;
import com.example.tool.util.DDUtil;
import com.example.tool.util.WDTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Component
public class InventoryShortageTasks {
    //冻品更新区域
    public static final String frozenProductsRangeAddressTemplate = "A%s:G%s";
    //冻品工作表
    private static final String frozenProductsKeyTemplate = "sys:frozenProductsWorkbookId:%s:%s";
    //冻品工作表
    private static final String frozenProductsWorkbookId = "ZX6GRezwJlyDpZnPI5PXgNoz8dqbropQ";
    //冻品机器人token
//    private static final String frozenProductsToken="a1791840494411b6ab4198a9b0903fea15d0a43fe4d91a2af6bf57581cf38576";
    private static final String frozenProductsToken = "101a5440fe4fff791a4c91b19baa4130bcad271cf240f5295cfdea4d3d13a191";
    //冻品机器人Secret
//    private static final String frozenProductsSecret="SEC1383d40c2e04e0f35815a77934bcc720412c552806a34aa955fdd56717276fe4";
    private static final String frozenProductsSecret = "SEC694fb5801f22ec15ede03797ffcabc69665b18d8ef8542fc9e1c0adc7ebd0829";
    //冻品数据表头
    public static final List<String> frozenProductsHeaderValues = Arrays.asList("货品编号", "货品名称", "仓库名称", "仓库编号", "可发库存", "采购在途", "排查时间");
    //冻品消息标题
    private static final String frozenProductsMsgTitle = "冻品品库存不足:详情可见";

    //常温更新区域
    public static final String roomTemperatureRangeAddressTemplate = "A%s:G%s";
    //常温工作表
    private static final String roomTemperatureWorkbookId = "N7dx2rn0JbN94QjnU5ONRMRNJMGjLRb3";
    //常温工作表
    private static final String roomTemperatureKeyTemplate = "sys:roomTemperatureWorkbookId:%s:%s";
    //常温机器人token
//    private static final String roomTemperatureToken="a1791840494411b6ab4198a9b0903fea15d0a43fe4d91a2af6bf57581cf38576";
    private static final String roomTemperatureToken = "101a5440fe4fff791a4c91b19baa4130bcad271cf240f5295cfdea4d3d13a191";
    //常温机器人Secret
//    private static final String roomTemperatureSecret="SEC1383d40c2e04e0f35815a77934bcc720412c552806a34aa955fdd56717276fe4";
    private static final String roomTemperatureSecret = "SEC694fb5801f22ec15ede03797ffcabc69665b18d8ef8542fc9e1c0adc7ebd0829";
    //常温消息标题
    private static final String roomTemperatureMsgTitle = "常温品库存不足:详情可见";
    //常温数据表头
    public static final List<String> roomTemperatureHeaderValues = Arrays.asList("货品编号", "货品名称", "仓库名称", "仓库编号", "可发库存", "采购在途", "排查时间");
    private static final String YYYY_MM = "yyyy-MM";
    private static final String YYYY_MM_DD = "yyyy-MM-dd";
    //保存时间值
    public static final Integer dataSaveDays = 7;
    //保存时间的单位
    public static final TimeUnit timeUnit = TimeUnit.DAYS;
    public static final Integer updateBatchSize = 1000;
    private static final String ddLinkUrl = "https://alidocs.dingtalk.com/i/nodes/%s";
    //    public static HashMap<String, WarehouseInterceptionConfig> WAREHOUSE_COLLECTION_DELAY_CONFIG=new HashMap<>();
    public static final List<String> frozenProductsWarehouseNos = Arrays.asList(WarehouseConfEnum.CQ_DP.getCode(), WarehouseConfEnum.HF_DP.getCode(),
            WarehouseConfEnum.TZ_DP.getCode(), WarehouseConfEnum.SH_DP.getCode(), WarehouseConfEnum.DX_DP.getCode(), WarehouseConfEnum.CS_DP.getCode(),
            WarehouseConfEnum.SY_DP.getCode(), WarehouseConfEnum.WH_DP.getCode());

    //    static {//揽收超时
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.LG_CW.getCode(),//苍南-龙港（常温仓）
//            new WarehouseInterceptionConfig(//龙港仓（常温）审单对接群
//            "gwva2dxOW4yp12j9Idyo6ArLVbkz3BRL",
//            WarehouseMsgSDConfEnum.LG_CW_SD.getSecret(),
//            WarehouseMsgSDConfEnum.LG_CW_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.CQ_DP.getCode(),//重庆-中通（冻品仓）
//            new WarehouseInterceptionConfig(//重庆仓（冻品）审单对接群
//            "YndMj49yWjmvkeaxi0Ax3gPm83pmz5aA",
//            WarehouseMsgSDConfEnum.CQ_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.CQ_DP_SD.getToken(),null,null));
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(  WarehouseConfEnum.JG_CW.getCode(),//广州-江高（常温仓）
//            new WarehouseInterceptionConfig(//江高仓（常温）督查群
//            "N7dx2rn0JbN94QjnU5O0xxpeJMGjLRb3",
//            WarehouseMsgSDConfEnum.JG_CW_SD.getSecret(),
//            WarehouseMsgSDConfEnum.JG_CW_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.HF_DP.getCode(),//合肥-肥西（冻品仓）
//            new WarehouseInterceptionConfig(//合肥仓（冻品）审单对接群
//            "AR4GpnMqJzYLxvAkTK6yNxKNVKe0xjE3",
//            WarehouseMsgSDConfEnum.HF_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.HF_DP_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.TZ_DP.getCode(),//济南-天泽（冻品仓）
//            new WarehouseInterceptionConfig(//天泽仓（冻品）审单对接群
//            "P7QG4Yx2Jp3NaeblUYLy4zdwV9dEq3XD",
//            WarehouseMsgSDConfEnum.TZ_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.TZ_DP_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.SH_DP.getCode(),//上海-上海（冻品仓）
//            new WarehouseInterceptionConfig(//上海仓 （冻品）审单对接群
//            "a9E05BDRVQNLOArKUmkd536nJ63zgkYA",
//            WarehouseMsgSDConfEnum.SH_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.SH_DP_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.DX_DP.getCode(),//广州-德信（冻品仓）
//            new WarehouseInterceptionConfig(//德信仓 （冻品）审单对接群
//            "93NwLYZXWybly4ANUvxydDd4VkyEqBQm",
//            WarehouseMsgSDConfEnum.DX_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.DX_DP_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.JX_CW.getCode(),//江西-南昌（常温仓）
//            new WarehouseInterceptionConfig(//江西仓（常温）审单对接群
//            "ZgpG2NdyVXaOEALjT3mxGpeRJMwvDqPk",
//            WarehouseMsgSDConfEnum.JX_CW_SD.getSecret(),
//            WarehouseMsgSDConfEnum.JX_CW_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.CS_DP.getCode(),//长沙-中通（冻品仓）
//            new WarehouseInterceptionConfig(//长沙仓（冻品）审单对接群
//            "7NkDwLng8ZK3GnEkTj7g3qDNWKMEvZBY",
//            WarehouseMsgSDConfEnum.CS_DP_SD.getSecret(),
//            WarehouseMsgSDConfEnum.CS_DP_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.CS_CW.getCode(),//湖南-长沙（常温仓）
//            new WarehouseInterceptionConfig(//长沙仓（常温）审单对接群
//            "kDnRL6jAJMDAYjEwHDgoayrwVyMoPYe1",
//            WarehouseMsgSDConfEnum.CS_CW_SD.getSecret(),
//            WarehouseMsgSDConfEnum.CS_CW_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.YW_CW.getCode(),//浙江-义乌（常温仓）
//            new WarehouseInterceptionConfig(//义乌仓 （常温）审单对接群
//            "7NkDwLng8ZK3GnEkTj7gwNRmWKMEvZBY",
//            WarehouseMsgSDConfEnum.YW_CW_SD.getSecret(),
//            WarehouseMsgSDConfEnum.YW_CW_SD.getToken(),null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.SY_DP.getCode(),//沈阳-天泽（冻品仓）
//            new WarehouseInterceptionConfig(//沈阳仓（冻品）审单对接群
//            "QG53mjyd80yjGN9lId1a1A9PW6zbX04v",
//            WarehouseMsgSDConfEnum.SY_DP_SD.getToken(),
//            WarehouseMsgSDConfEnum.SY_DP_SD.getToken(),
//            null,null));
//
//            WAREHOUSE_COLLECTION_DELAY_CONFIG.put(WarehouseConfEnum.WH_DP.getCode(),//武汉（冻品仓）
//            new WarehouseInterceptionConfig(//武汉仓（冻品）审单对接群
//            "Gl6Pm2Db8DemzxdRFqKmx300WxLq0Ee4",
//            WarehouseMsgSDConfEnum.WH_DP_SD.getToken(),
//            WarehouseMsgSDConfEnum.WH_DP_SD.getToken(),null,null));
//    }
//    @Scheduled(cron = "0 0 9 * * ?", zone = "Asia/Shanghai")
    public void scheduledImportClaims() {
        log.info("---------ERP库存统计定时任务开始----------");
        List<StockSearch2Response.Detail> stockDetail = findStockDetail();
        processingData(stockDetail);
        log.info("---------ERP库存统计定时任务结束----------");
    }

    public List<StockSearch2Response.Detail> findStockDetail() {
        DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime endTime = LocalDateTime.now();
        String endSearchTime = endTime.format(FORMATTER);
        String startSearchTime = endTime.minusHours(24).format(FORMATTER);
        List<StockSearch2Response.Detail> allStockDetail = new ArrayList<>();
        StockSearch2Response stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, 1, 0);
//        List<StockSearch2Response.Detail> details = stockSearch2Response.getDetailList();
        Integer total = stockSearch2Response.getTotal();
        int pageSize = 1000;
        if (total > 0) {
            int totalPages = (int) Math.ceil((double) total / pageSize);
            for (int pageNo = 0; pageNo < totalPages; pageNo++) {
                stockSearch2Response = WDTUtil.stockSpecSearch2(startSearchTime, endSearchTime, pageSize, pageNo);
                allStockDetail.addAll(stockSearch2Response.getDetailList());
            }
        }
        allStockDetail = allStockDetail.stream().distinct().collect(Collectors.toList());
        return allStockDetail;
    }

    public void processingData(List<StockSearch2Response.Detail> stockDetail) {
        List<String> specNos = stockDetail.stream().map(StockSearch2Response.Detail::getSpecNo).distinct().collect(Collectors.toList());
        List<String> goodNos = new ArrayList<>();
        for (String specNo : specNos) {
            GoodsSearchResponse goodsSearchResponse = WDTUtil.goodsSearchSpecNo(specNo);
            for (GoodsSearchResponse.GoodsSearchGoodsDto goodsDto : goodsSearchResponse.getGoodsInfos()) {
                for (GoodsSearchResponse.GoodsSearchSpecDto specDtoss : goodsDto.getSpecDtos()) {
                    if (ObjectUtil.equal(specDtoss.getProp6(), "出售ing")) {
                        goodNos.add(goodsDto.getGoodsNo());
                    }
                }
            }
        }

        goodNos = goodNos.stream().distinct().collect(Collectors.toList());
        List<String> finalGoodNos = goodNos;
        stockDetail = stockDetail.stream().filter(sd -> {
            if (!finalGoodNos.contains(sd.getGoodsNo())) {
                return false;
            }
            if (sd.getAvailableSendStock().compareTo(BigDecimal.ZERO) <= 0 && sd.getPurchaseNum().compareTo(new BigDecimal("200")) > 0) {
                return true;
            }

//        boolean b = sd.getAvailableSendStock().divide(sd.getNumYesteray(), 10, RoundingMode.HALF_UP).compareTo(BigDecimal.ONE) < 0;
//        if(!b){return false;}

//        BigDecimal newNum=sd.getPurchaseNum().add(sd.getAvailableSendStock());
//        return newNum.compareTo(sd.getAvailableSendStock())< 0;
            return false;
        }).collect(Collectors.toList());

        SimpleDateFormat YYYY_MM_SDF = new SimpleDateFormat(YYYY_MM);
        SimpleDateFormat YYYY_MM_DD_SDF = new SimpleDateFormat(YYYY_MM_DD);
        Date date = new Date();
//                String yyyyMM = YYYY_MM_SDF.format(date);
        String yyyyMMdd = YYYY_MM_DD_SDF.format(date);
//                Calendar calendar = Calendar.getInstance();
//                calendar.setTime(date); // 设置Calendar的时间为当前日期
//                calendar.add(Calendar.MONTH, -1); // 月份减1
//                Date newDate = calendar.getTime();
//                String newYyyyMMdd = YYYY_MM_DD_SDF.format(newDate);
        List<StockSearch2Response.Detail> frozenProducts = stockDetail.stream().filter(sd -> frozenProductsWarehouseNos.contains(sd.getWarehouseNo())).collect(Collectors.toList());
        if (!frozenProducts.isEmpty()) {
//            Map<String, List<StockSearch2Response.Detail>> collect = frozenProducts.stream().collect(Collectors.groupingBy(StockSearch2Response.Detail::getWarehouseNo));
//            for(String key:collect.keySet()){
//            DDUtil.delWorkbook(frozenProductsWorkbookId,newYyyyMMdd);
//            List<StockSearch2Response.Detail> details = collect.get(key);
//                    DDUtil.createSheets(frozenProductsWorkbookId, yyyyMMdd);
//                    JSONArray sheets = DDUtil.getSheets(frozenProductsWorkbookId).getJSONArray("value");
//                    for (int i = 0; i < sheets.size(); i++) {
//                        JSONObject sheet = sheets.getJSONObject(i);
//                        String sheetId = sheet.getString("name");
//                        if (!ObjectUtil.equal(sheetId, yyyyMMdd)) {
//                            DDUtil.deleteSheet(frozenProductsWorkbookId, sheetId);
//                        }
//                    }
//
            List<List<String>> values = frozenProducts.stream().map(fp -> Arrays.asList(fp.getGoodsNo(), fp.getGoodsName(), fp.getWarehouseName(), fp.getWarehouseNo(), fp.getAvailableSendStock().toString(), fp.getPurchaseNum().toString(), yyyyMMdd)).collect(Collectors.toList());
            DDUtil.updateAiExcelSendMsg(frozenProductsWorkbookId, frozenProductsSecret, frozenProductsToken, null, null, values, yyyyMMdd, frozenProductsHeaderValues, frozenProductsMsgTitle, "", "", updateBatchSize);
//
        }


        List<StockSearch2Response.Detail> roomTemperature = stockDetail.stream().filter(sd -> !frozenProductsWarehouseNos.contains(sd.getWarehouseNo())).collect(Collectors.toList());
        if (!roomTemperature.isEmpty()) {
            try {
                // 休眠1000毫秒（1秒）
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
            }
//                    DDUtil.createSheets(roomTemperatureWorkbookId, yyyyMMdd);
//                    JSONArray sheets = DDUtil.getSheets(roomTemperatureWorkbookId).getJSONArray("value");
//                    for (int i = 0; i < sheets.size(); i++) {
//                        JSONObject sheet = sheets.getJSONObject(i);
//                        String sheetId = sheet.getString("name");
//                        if (!ObjectUtil.equal(sheetId, yyyyMMdd)) {
//                            DDUtil.deleteSheet(roomTemperatureWorkbookId, sheetId);
//                        }
//                    }
            List<List<String>> values = roomTemperature.stream().map(fp -> Arrays.asList(fp.getGoodsNo(), fp.getGoodsName(), fp.getWarehouseName(), fp.getWarehouseNo(), fp.getAvailableSendStock().toString(), fp.getPurchaseNum().toString(), yyyyMMdd)).collect(Collectors.toList());
            DDUtil.updateAiExcelSendMsg(roomTemperatureWorkbookId, roomTemperatureSecret, roomTemperatureToken, null, null, values, yyyyMMdd, roomTemperatureHeaderValues, roomTemperatureMsgTitle, "", "", updateBatchSize);
//            }

        }
    }
}

